Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: [],
    block: ['0', '0-0'],
    selectedRentRange: "", // 储存租金范围选项  
    rent: {
      value: '不限',
      options: [{
          value: '不限',
          label: '不限',
        },
        {
          value: '1000-2000',
          label: '1000-2000',
        },
        {
          value: '2000-3000',
          label: '2000-3000',
        },
        {
          value: '3000-4000',
          label: '3000-4000',
        },
      ],
    },
    rentList: [],
    selectedSortRange: "",
    sort: {
      value: '默认排序',
      options: [{
          value: '默认排序',
          label: '默认排序',
        },
        {
          value: '价格最低',
          label: '价格最低',
        },
        {
          value: '时间最新',
          label: '时间最新',
        },
        // {
        //   value: '离我最近',
        //   label: '离我最近',
        // },
      ],
    },
    value: '',
    value1: 0,
    labels: ['东', '南', '西', '北'],
    value2: 0,
    area: ['100', '120', '30', '40'],
    value3: 0,
    indoor: ['一居', '二居', '三居', '四居'],
    apartList: [],
    isAreaPickerOpen: false,
    filteredApartments: [], // 存储过滤后的公寓列表  
  },
  // 区域
  district() {
    wx.request({
      url: 'http://localhost:8080/ihome/district/district',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (resp => {
        console.log(resp.data)
        this.setData({
          options: resp.data
        })
      })
    })
  },
  onChange(e) {
    this.setData({
      block: e.detail.value,
    });
    console.log(e.detail.value)
  },
  // 朝向
  onChange1(e) {
    // 获取用户选择的朝向索引
    const selectedOriIndex = e.detail.value;
    const selectedOri = this.data.labels[selectedOriIndex]; // 根据索引获取对应面积 
    console.log(selectedOri)
    this.setData({
      value1: selectedOriIndex
    });
    this.OrientationList(selectedOri)
  },
  //面积
  onChange2(e) {
    // 获取用户选择的面积  
    const selectedAreaIndex = e.detail.value; // 这里获取选中的索引  
    const selectedArea = this.data.area[selectedAreaIndex]; // 根据索引获取对应面积  
    this.setData({
      value2: selectedAreaIndex
    });
    console.log(selectedArea)
    // 调用获取公寓列表的方法  
    this.AreaApartList(selectedArea);
  },
  //居室
  onChange3(e) {
    // 获取用户选择的面积  
    const selectedIndoorIndex = e.detail.value; // 这里获取选中的索引  
    const selectedIndoor = this.data.indoor[selectedIndoorIndex]; // 根据索引获取对应面积  
    this.setData({
      value3: selectedIndoorIndex
    });
    console.log(selectedIndoor)
    this.indoorList(selectedIndoor)
  },



  // onChange1(e) {
  //   // 获取用户选择的朝向索引  
  //   const selectedOriIndex = e.detail.value;
  //   const selectedOri = this.data.labels[selectedOriIndex];
  //   console.log('Selected orientation:', selectedOri);

  //   this.setData({
  //     value1: selectedOriIndex,
  //     value2: 0, // 重置面积索引  
  //     value3: 0 // 重置居室索引  
  //   });

  //   this.filterApartments(selectedOri, null, null); // 过滤公寓列表  
  // },

  // onChange2(e) {
  //   // 获取用户选择的面积  
  //   const selectedAreaIndex = e.detail.value;
  //   const selectedArea = this.data.area[selectedAreaIndex];
  //   console.log('Selected area:', selectedArea);

  //   this.setData({
  //     value2: selectedAreaIndex,
  //     value1: 0, // 重置朝向索引  
  //     value3: 0 // 重置居室索引  
  //   });

  //   this.filterApartments(null, selectedArea, null); // 过滤公寓列表  
  // },

  // onChange3(e) {
  //   // 获取用户选择的居室  
  //   const selectedIndoorIndex = e.detail.value;
  //   const selectedIndoor = this.data.indoor[selectedIndoorIndex];
  //   console.log('Selected indoor:', selectedIndoor);

  //   this.setData({
  //     value3: selectedIndoorIndex,
  //     value1: 0, // 重置朝向索引  
  //     value2: selectedAreaIndex // 重置面积索引  
  //   });

  //   this.filterApartments(null, null, selectedIndoor); // 过滤公寓列表  
  // },



  
  // 租金
  handlerent(e) {
    const selectedValue = e.detail.value; // 获取选择的值  
    this.setData({
      selectedRentRange: selectedValue,
      'rent.value': selectedValue // 更新租金范围的值  
    });
    // 基于选定的租金范围更新 priceMin 和 priceMax  
    if (selectedValue === '不限') { // 检查是否选择“不限”  
      this.setData({
        priceMin: null,
        priceMax: null
      });
    } else {
      const [min, max] = selectedValue.split('-').map(Number);
      // 检查租金范围是否有效  
      const isValidRange = !isNaN(min) && !isNaN(max) && min <= max;
      this.setData({
        priceMin: isValidRange ? min : null,
        priceMax: isValidRange ? max : null
      });
    }
    console.log(selectedValue);
    this.RentApartList(); // 应用新的筛选条件  
  },
  // 排序
  handlesort(e) {
    const selectedSort = e.detail.value;
    this.setData({
      selectedSortRange: selectedSort,
      'sort.value': selectedSort
    });
    //console.log(apartments)
    console.log(selectedSort)
    if (selectedSort === '默认排序') {
      this.getData()
      console.log('默认', this.data.apartList)
    } else if (selectedSort === '价格最低') {
      this.SortApartList();
    } else if (selectedSort === '时间最新') {
      this.TimeApartList()
    }
  },

  formSubmit(e) {
    this.setData({})
    console.log('form发生了submit事件')
    // 关闭所有选择器
    this.setData({
      isAreaPickerOpen: false
    });
  },

  formReset(e) {
    this.setData({
      value1: 0,
      value2: 0,
      value3: 0,
    })
    console.log('form发生了reset事件')
  },
  getData() {
    wx.request({
      url: 'http://localhost:8080/ihome/apartment/list',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },

      success: (resp) => {
        console.log(resp)
        const apartList = resp.data.rows;
        this.setData({
          apartList: apartList
        })
      }
    });
  },
  RentApartList() {
    // 创建请求数据对象  
    let requestData = {
      pageNum: 1,
      pageSize: 10
    };
    // 仅在价格范围不为空时添加相应的参数  
    if (this.data.priceMin !== null) {
      requestData.priceMin = this.data.priceMin; // 使用设置的最低价格  
    }
    if (this.data.priceMax !== null) {
      requestData.priceMax = this.data.priceMax; // 使用设置的最高价格  
    }
    wx.request({
      url: 'http://localhost:8080/ihome/apartment/list',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      data: requestData,
      success: (resp) => {
        this.setData({
          apartList: resp.data.rows // 更新公寓列表数据  
        });
      }
    });
  },
  SortApartList() {
    // 创建请求数据对象  
    // let requestData = {
    //   pageNum: 1,
    //   pageSize: 10
    // };
    wx.request({
      url: 'http://localhost:8080/ihome/apartment/list?pageNum=1&pageSize=10',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      data: {
        createTime: this.data.createTime, // 创建时间  
      },
      success: (resp) => {
        let apartments = resp.data.rows;
        apartments = apartments.sort((a, b) => Number(a.priceMin) - Number(b.priceMin));
        console.log(resp)
        this.setData({
          apartList: apartments // 更新公寓列表数据  
        });
        console.log(resp.data.rows)
      }
    })
  },
  TimeApartList() {
    // 创建请求数据对象  
    // let requestData = {
    //   pageNum: 1,
    //   pageSize: 10
    // };
    wx.request({
      url: 'http://localhost:8080/ihome/apartment/list?pageNum=1&pageSize=10',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      // data: {
      //   requestData,
      // },
      success: (resp) => {
        let apartments = resp.data.rows;
        apartments = apartments.sort((a, b) => {
          // 解析 ISO 8601 日期时间字符串为 Date 对象
          const dateA = new Date(a.createTime);
          const dateB = new Date(b.createTime);
          return dateB - dateA; // 降序排序
        });
        console.log(resp),
          this.setData({
            apartList: apartments // 更新公寓列表数据  
          }),
          console.log(resp.data.rows)
      }
    })
  },
  AreaApartList(selectedArea) {
    wx.request({
      url: 'http://localhost/dev-api/ihome/apartment/list?pageNum=1&pageSize=10',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      success: (resp) => {
        const apartments = resp.data.rows;
        const filteredApartments = apartments.filter(apartment => {
          // 检查面积是否与所选面积相等
          return Number(apartment.area) === Number(selectedArea);
        });
        this.setData({
          apartList: filteredApartments // 更新公寓列表数据  
        })
      }
    })
  },
  OrientationList(selectedOri) {
    wx.request({
      url: 'http://localhost/dev-api/ihome/apartment/list?pageNum=1&pageSize=10',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      success: (resp) => {
        const apartments = resp.data.rows;
        const filteredApartments = apartments.filter(apartment => {
          // 确保 apartment.orientation 未定义，并且对比 selectedOriIndex  
          return apartment.orientation === selectedOri;
        });
        console.log("朝向",filteredApartments)
        this.setData({
          apartList: filteredApartments // 更新公寓列表数据  
        })
        console.log('朝向', this.data.apartList)
      }
    })
  },
  indoorList(selectedIndoor) {
    wx.request({
      url: 'http://localhost/dev-api/ihome/apartment/list?pageNum=1&pageSize=10',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 获取存储的 token  
      },
      success: (resp) => {
        const apartments = resp.data.rows;

        // 过滤出与所选房间类型匹配的公寓
        const filteredApartments = apartments.filter(apartment => {
          const houseType = apartment.houseType; // 获取当前公寓的房间类型
          if (typeof houseType === 'string' && houseType.trim() === selectedIndoor) {
            // 如果房间类型相等，输出公寓信息
            console.log('匹配的公寓信息:', apartment);
          }
          return typeof houseType === 'string' && houseType.trim() === selectedIndoor;
        });
        console.log('过滤后的公寓信息:', filteredApartments); // 输出过滤后的结果
        this.setData({
          apartList: filteredApartments // 更新公寓列表数据  
        })
      }
    })
  },
  filterApartments(selectedOri, selectedArea, selectedIndoor) {
    const apartments = this.data.apartList; // 获取原始公寓数据  
    console.log('======',this.data.apartList)
    let filtered = apartments;
    // if (selectedOri) {
    //   filtered = filtered.filter(apartment => apartment.orientation === selectedOri);
    // }
    // if (selectedArea) {
    //   filtered = filtered.filter(apartment => apartment.area === selectedArea);
    // }
    // if (selectedIndoor) {
    //   filtered = filtered.filter(apartment => apartment.indoor === selectedIndoor);
    // }

    // 如果没有任何筛选条件，则显示所有房子信息  
    if (!selectedOri && !selectedArea && !selectedIndoor) {
      filtered = apartments;
    }

    console.log('Filtered apartments:', filtered);
    this.setData({
      apartList: filtered // 更新过滤后的公寓列表  
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData()
    this.RentApartList()
    this.SortApartList()
    this.TimeApartList()
    this.district()
    // this.AreaApartList()
    // this.OrientationList()
    // this.indoorList()
    this.filterApartments()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    wx.showToast({
      title: '没有更多数据了',
      icon: 'none'
    })
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})